<template>
    <view>
        <map ref="map" :style="{ width: '100%', height: `calc(100vh - ${minusHeight}rpx)` }" :latitude="latitude"
            :longitude="longitude" :scale="scale" :polygons="polygons" :markers="markers" @callouttap="onCalloutTap">
            <cover-view slot="callout">
                <cover-view v-for="(item, index) in data" :key="index" class="customCallout" :marker-id="item.id">
                    <cover-view class="content">
                        <!-- <cover-image class="icon" :key="item.id" :src="coverImage" /> -->
                        <cover-view class="text">{{ item.title || '未命名' }}</cover-view>
                    </cover-view>
                </cover-view>
            </cover-view>
        </map>
    </view>
</template>
<script>
export default {
    data() {
        return {
            latitude: 34.800403,
            longitude: 113.660274,
            polygons: [],
            markers: [],
            scale: 11,
            currentLocation: null  // 添加当前位置数据
        }
    },
    props: {
        minusHeight: {
            type: Number,
            default: 176
        },
        data: {
            type: Array,
            default: () => []
        },
        type: {
            type: String,
            default: ''
        }
    },
    computed: {
        coverImage() {
            switch (this.type) {
                case 'land':
                    return '/static/tabbar/tudiHL.png'
                case 'garden':
                    return '/static/tabbar/yuanquHL.png'
                case 'building':
                    return '/static/tabbar/louyuHL.png'
                default:
                    return '/static/zuobiao.png'
            }
        }
    },
    watch: {
        data: {
            handler(newVal) {
                if (newVal?.length) {
                    // 确保在数据变化时重新初始化地图
                    this.$nextTick(() => {
                        this.initMap()
                        this.adjustMapCenter()
                    })
                } else {
                    // 如果没有数据，清空地图标记
                    this.polygons = []
                    this.markers = []
                }
            },
            immediate: true,
            deep: true  // 添加深度监听确保能捕获数据变化
        },
        currentLocation: {
            handler(newVal) {
                if (newVal) {
                    this.latitude = newVal.latitude
                    this.longitude = newVal.longitude
                }
            },
            immediate: true
        }
    },
    mounted() {
        this.getCurrentLocation()
        this.initMap()
    },
    methods: {
        getCurrentLocation() {
            uni.getLocation({
                type: 'gcj02',
                success: (res) => {
                    this.currentLocation = {
                        latitude: res.latitude,
                        longitude: res.longitude
                    }
                    // 添加当前位置标记
                    this.markers.push({
                        id: 'currentLocation',
                        latitude: res.latitude,
                        longitude: res.longitude,
                        width: 40,
                        height: 40,
                        anchor: {
                            x: 0.5,
                            y: 0.5
                        },
                        iconPath: '/static/wodeweizhi.png',
                        customCallout: {
                            display: 'ALWAYS',
                            anchorY: 0,
                            anchorX: 0.5,
                            zIndex: 2
                        }
                    })
                },
                fail: (err) => {
                    console.error('获取位置失败：', err)
                    uni.showToast({
                        title: '获取位置失败',
                        icon: 'none'
                    })
                }
            })
        },
        adjustMapCenter() {
            if (!this.data?.length) return

            try {
                const coordinate = this.data[0].coordinate ? JSON.parse(this.data[0].coordinate) : null
                if (coordinate?.length) {
                    const latSum = coordinate.reduce((sum, point) => sum + (+point.lat), 0)
                    const lngSum = coordinate.reduce((sum, point) => sum + (+point.lng), 0)
                    this.latitude = latSum / coordinate.length
                    this.longitude = lngSum / coordinate.length

                    // 根据多边形的大小自动调整缩放级别
                    const maxLat = Math.max(...coordinate.map(point => +point.lat))
                    const minLat = Math.min(...coordinate.map(point => +point.lat))
                    const maxLng = Math.max(...coordinate.map(point => +point.lng))
                    const minLng = Math.min(...coordinate.map(point => +point.lng))

                    // 根据经纬度差值计算合适的缩放级别
                    const latDiff = maxLat - minLat
                    const lngDiff = maxLng - minLng
                    const maxDiff = Math.max(latDiff, lngDiff)

                    // 根据差值设置缩放级别，差值越大，缩放级别越小
                    if (maxDiff > 0.1) this.scale = 9
                    else if (maxDiff > 0.05) this.scale = 10
                    else if (maxDiff > 0.01) this.scale = 11
                    else this.scale = 12
                }
            } catch (e) {
                console.error(e)
            }
        },
        initMap() {
            if (!this.data?.length) return

            try {
                this.polygons = []
                this.markers = []

                // 重新生成多边形和标记点
                this.data.forEach(item => {
                    if (item.coordinate) {
                        // 处理多边形情况
                        const coordinate = JSON.parse(item.coordinate)
                        if (coordinate?.length) {
                            // 添加多边形
                            const points = coordinate.map(l => ({
                                latitude: +l.lat,
                                longitude: +l.lng
                            }))
                            this.polygons.push({
                                points,
                                strokeColor: '#000',
                                strokeWidth: 1,
                                fillColor: item.color || '#ff000033'
                            })

                            // 计算多边形中心点
                            const latSum = coordinate.reduce((sum, point) => sum + (+point.lat), 0)
                            const lngSum = coordinate.reduce((sum, point) => sum + (+point.lng), 0)
                            const centerLat = latSum / coordinate.length
                            const centerLng = lngSum / coordinate.length

                            this.addMarker(item, centerLat, centerLng)
                        }
                    } else if (item.lat && item.lng) {
                        // 如果没有coordinate但有lat和lng，直接添加标记点
                        this.addMarker(item, +item.lat, +item.lng)
                    }
                })
            } catch (e) {
                console.error(e)
            }
        },
        addMarker(item, lat, lng) {
            this.markers.push({
                id: item.id,
                latitude: lat,
                longitude: lng,
                // 调整单个坐标点的图标尺寸为20x20
                width: item.coordinate ? 1 : 15,
                height: item.coordinate ? 1 : 18,
                anchor: {
                    x: 0.5,
                    y: 0.5
                },
                iconPath: item.coordinate ? '/static/touming.png' : '/static/marker-icon.png',
                customCallout: {
                    display: 'ALWAYS',
                    anchorY: item.coordinate ? 1 : 0,
                    anchorX: 0.5,
                    zIndex: 2
                }
            })
        },
        onCalloutTap(e) {
            const markerId = e.markerId
            const item = this.data.find(item => item.id === markerId)
            if (item) {
                this.$emit('markerClick', item)
            }
        }
    }
}
</script>

<style>
.customCallout {
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 40rpx;
    padding: 12rpx 16rpx;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    width: fit-content;
    display: inline-block;
}

.content {
    display: flex;
    align-items: center;
    gap: 4rpx;
    width: fit-content;
    white-space: nowrap;
    line-height: 36rpx;
}

.icon {
    width: 36rpx;
    height: 36rpx;
    display: block;
}

.text {
    font-size: 28rpx;
    color: #1C1714;
    padding: 0;
    line-height: 36rpx;
}
</style>